import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";
import { getRequest } from "../util/Net";

interface FetchProfileResponse {
  uid: number;
  userName: string;
  name: string;
  roleName: string;
}

interface ProfileState {
  loaded: boolean;
  uid: number;
  userName: string;
  name: string;
  roleName: string;
}

const initialState: ProfileState = {
  loaded: false,
  uid: 0,
  userName: '',
  name: '',
  roleName: ''
};

const fetchProfile = createAsyncThunk('api/fetchProfile', async () => {
  const response = await getRequest<FetchProfileResponse, null>({
    url: '/account/profile'
  });
  return response.data;
});

const profileSlice = createSlice({
  name: 'profile',
  initialState: initialState,
  reducers: {
    clear: (state) => {
      state.loaded = false;
      state.name = '';
      state.roleName = '';
      state.uid = 0;
      state.userName = '';
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchProfile.fulfilled, (state, action) => {
      const result = action.payload.result;
      state.loaded = true;
      state.uid = result.uid;
      state.userName = result.userName;
      state.name = result.name;
      state.roleName = result.roleName;
    })
  }
});

export default profileSlice.reducer;
export const profileActions = { ...profileSlice.actions, fetchProfile };
export const selectProfileLoaded = (root: RootState) => root.profileReducer.loaded;
export const selectProfileUid = (root: RootState) => root.profileReducer.uid;
export const selectProfileUserName = (root: RootState) => root.profileReducer.userName;
export const selectProfileName = (root: RootState) => root.profileReducer.name;
export const selectProfileRoleName = (root: RootState) => root.profileReducer.roleName;